package com.hb.umsp.contraller;

import com.hb.umsp.entity.HbUser;
import com.hb.umsp.service.LoginUser;
import com.hb.umsp.service.UserService;
import com.hb.umsp.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
public class LoginUserContraller {

    @Autowired
    LoginUser loginUser;

    @Autowired
    UserService userService;

    /**
     * 登录进行域名验证并获取token
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @RequestMapping("/login")
    public JsonResult login(@RequestParam String username,@RequestParam String password){
        if (username == null || "".equals(username)) {
            return new JsonResult("50008","用户名为空");
        }
        String token = loginUser.login(username,password);
        return new JsonResult("20000",token);
    }

    /**
     * 登录进行域名验证并获取token
     * @return
     */
    @RequestMapping("/outlogin")
    public JsonResult outlogin(HttpServletRequest request, HttpServletResponse response){
        String token = request.getHeader("token");
        response.setHeader("token",null);
        return new JsonResult("20000","登出成功");
    }

    /**
     * 根据token获取用户信息
     * @param request
     * @return
     */
    @RequestMapping("getUserByToken")
    public JsonResult getUserByToken(HttpServletRequest request){
        String token = request.getHeader("token");
        if (token == null || "".equals(token)) {
            return new JsonResult("50008","未获取token");
        }
        HbUser hbUser = userService.findHbUserByToken(token);
        if (hbUser == null || "".equals(hbUser)) {
            return new JsonResult("00000","未查询到用户对象");
        }
        if ("".equals(hbUser.getUsername())) {
            return new JsonResult("00000","用户名不存在");
        }
        return new JsonResult("20000",hbUser);
    }

    @RequestMapping("getUser")
    public JsonResult getUser(@RequestBody(required = false) HbUser hbUser){

        List<HbUser> hbUsers = userService.findUser(hbUser);

        return new JsonResult("20000",hbUsers);
    }

    /**
     * 根据token获取角色信息
     * @param request
     * @return
     */
    @RequestMapping("getUserRole")
    public JsonResult getUserRole(HttpServletRequest request){
        String token = request.getHeader("token");
        if (token == null || "".equals(token)) {
            return new JsonResult("50008","未获取token");
        }
        List<HbUser> list = userService.selectUserToMenuGrpByToken(token);
        if (list.size() <= 0) {
            return new JsonResult("50008","未查询出数据");
        }
        return new JsonResult("20000",list);
    }
}
